package com.sky.controller.User;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.User;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.security.Signature;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 订单
 */
@RestController("userOrderController")
@RequestMapping("/user/order")
@Slf4j
@Api(tags = "C端订单接口")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;


    @GetMapping("/reminder/{id}")
    @ApiOperation("用户催单")
    public Result reminder(@PathVariable("id") Long id) {
        orderService.reminder(id);
        return Result.success();
    }
    @PostMapping("/repetition/{id}")
    @ApiOperation("再来一单")
    public Result repetition(@PathVariable Long id) {
        orderService.repetition(id);
        return Result.success();
    }


    @PutMapping("/cancel/{id}")
    @ApiOperation("取消订单")
    public Result cancel(@PathVariable("id") Long id) throws Exception {
        orderService.userCancelById(id);
        return Result.success();
    }

    @GetMapping("/orderDetail/{id}")
    @ApiOperation("查询订单详情")
    public Result<OrderVO> details(@PathVariable("id") Long id) {
        OrderVO orderVO = orderService.details(id);
        return Result.success(orderVO);
    }

    @GetMapping("/historyOrders")
    public Result<PageResult> historyOrders(Integer page,Integer pageSize,Integer status) {

        PageResult pageResult = orderService.historyOrders(page,pageSize,status);

        return Result.success(pageResult);
    }


    @PostMapping("/submit")
    @ApiOperation("用户下单")
    public Result<OrderSubmitVO> submit(@RequestBody OrdersSubmitDTO ordersSubmitDTO) {
        log.info("用户下单：{}", ordersSubmitDTO);
        OrderSubmitVO orderSubmitVO = orderService.submitOrder(ordersSubmitDTO);
        return Result.success(orderSubmitVO);
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @PutMapping("/payment")
    @ApiOperation("订单支付")
    public Result<JSONObject> payment(@RequestBody OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        User uu = userMapper.getById(BaseContext.getCurrentId());
        String prepay_id="wowowowowowowoowwowo";
        CloseableHttpClient kk = HttpClients.createDefault();
        HttpPost pp = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi");
        JSONObject jsob = new JSONObject();
        jsob.put("appid",weChatProperties.getAppid());
        jsob.put("mchid",weChatProperties.getMchid());
        jsob.put("description","订单是我的爱吃的外卖");
        JSONObject amount = new JSONObject();
        amount.put("total",1);
        amount.put("currency","CNY");
        jsob.put("amount",amount);
        jsob.put("out_trade_no",ordersPaymentDTO.getOrderNumber());
        jsob.put("notify_url",weChatProperties.getNotifyUrl());
        JSONObject payer = new JSONObject();
        payer.put("openid",uu.getOpenid());
        jsob.put("payer",payer);
        StringEntity strEntity = new StringEntity(jsob.toString());
        pp.setEntity(strEntity);

        CloseableHttpResponse res = kk.execute(pp);//发送请求的到prepay_id
        System.out.println(res.getEntity());
        String body = res.getEntity().toString();
//        prepay_id =  JSON.parseObject(body).getString("prepay_id");



        JSONObject jo = new JSONObject();
        String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
        String nonceStr = RandomStringUtils.randomNumeric(32);







        jo.put("timeStamp", timeStamp);
        jo.put("nonceStr", nonceStr);
        jo.put("package", "prepay_id=" + prepay_id);
        jo.put("signType", "RSA");
        jo.put("paySign", "sksksksksksksksksksks");
        return Result.success(jo);


    }

}
